package org.jeecg.modules.wangyue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wangyue.constant.*;
import org.jeecg.modules.wangyue.entity.*;
import org.jeecg.modules.wangyue.mapper.*;
import org.jeecg.modules.wangyue.model.req.ReqPointsModel;
import org.jeecg.modules.wangyue.service.IPointsFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Description: 积分流水表
 * @Author: jeecg-boot
 * @Date:   2023-09-08
 * @Version: V1.0
 */
@Service
public class PointsFlowServiceImpl extends ServiceImpl<PointsFlowMapper, PointsFlow> implements IPointsFlowService {

    @Autowired
    private PointsFlowMapper pointsFlowMapper;
    @Autowired
    private UserRoleInfoMapper userRoleInfoMapper;
    @Autowired
    private ConfigurationMapper configurationMapper;
    @Autowired
    private UserBasicMapper userBasicMapper;
    @Autowired
    private CapitalFlowMapper capitalFlowMapper;
    @Autowired
    private CompanyFlowMapper companyFlowMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> advertisementGainPoints(UserRoleInfo userRoleInfo) {
        String userId = userRoleInfo.getUserId();
        String userType = userRoleInfo.getUserType();
        if(oConvertUtils.isEmpty(userId) || oConvertUtils.isEmpty(userType)){
            return Result.error("必输项不能为空");
        }

        QueryWrapper<Configuration> configurationQueryWrapper = new QueryWrapper<>();
        configurationQueryWrapper.eq("id", ConfigParamConstant.advertisementPoints);
        configurationQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        Configuration configuration = configurationMapper.selectOne(configurationQueryWrapper);
        if (oConvertUtils.isNotEmpty(configuration) && oConvertUtils.isNotEmpty(configuration.getParamValue())){
            //1.查询用户积分(行上锁)
            UserRoleInfo uri = userRoleInfoMapper.queryOneForUpdate(userId, userType);

            //2.增加积分
            UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
            userRoleInfoUpdateWrapper.eq("user_id", uri.getUserId());
            userRoleInfoUpdateWrapper.eq("user_type", uri.getUserType());
            userRoleInfoUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
            userRoleInfoUpdateWrapper.set("points", uri.getPoints() + Integer.valueOf(configuration.getParamValue()));
            int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
            if(userRoleInfoNum < 1){
                throw new RuntimeException("积分获取-失败(1)");
            }

            //3.积分流水表增加数据
            PointsFlow pointsFlow = new PointsFlow();
            pointsFlow.setUserId(uri.getUserId());
            pointsFlow.setUserType(uri.getUserType());
            pointsFlow.setChangeType(PointsFlowConstant.viewAdvertisements); //1-观看广告
            pointsFlow.setChangeName(PointsFlowConstant.viewAdvertisementsName); //观看广告
            pointsFlow.setChangePoints(Integer.valueOf(configuration.getParamValue()));
            pointsFlow.setUpOrDown(PointsFlowConstant.points_up);
            int pointsFlowNum = pointsFlowMapper.insert(pointsFlow);
            if(pointsFlowNum < 1){
                throw new RuntimeException("积分获取-失败(2)");
            }

            return Result.OK("积分获取成功");
        }else{
            return Result.error("广告获取积分-参数配置有问题！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> redemptionAmountOfPoints(ReqPointsModel reqPointsModel) {
        String userId = reqPointsModel.getUserId();
        String userType = reqPointsModel.getUserType();
        String points = reqPointsModel.getPoints();
        String amount = reqPointsModel.getAmount();
        if(oConvertUtils.isEmpty(userId) || oConvertUtils.isEmpty(userType) || oConvertUtils.isEmpty(points) || oConvertUtils.isEmpty(amount)){
            return Result.error("必输项不能为空");
        }

        //1.查询用户积分和金额(行上锁)
        UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(userId, userType);
        if(Integer.valueOf(points) > userRoleInfo.getPoints()){
            return Result.error("积分不足,兑换失败");
        }
        //查询账号
        UserBasic userBasic = userBasicMapper.selectById(userRoleInfo.getUserId());

        //2.改变积分和金额
        UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
        userRoleInfoUpdateWrapper.eq("user_id", userRoleInfo.getUserId());
        userRoleInfoUpdateWrapper.eq("user_type", userRoleInfo.getUserType());
        userRoleInfoUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
        userRoleInfoUpdateWrapper.set("points", userRoleInfo.getPoints() - Integer.valueOf(points)); //扣掉积分
        userRoleInfoUpdateWrapper.set("balance", userRoleInfo.getBalance().add(new BigDecimal(amount))); //余额增加积分兑换的额度
        userRoleInfoUpdateWrapper.set("total_amount", userRoleInfo.getTotalAmount().add(new BigDecimal(amount))); //总金额增加金粉兑换的额度
        int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
        if(userRoleInfoNum < 1){
            throw new RuntimeException("积分兑换-失败(1)");
        }

        //3.积分流水表、资金流水表、公司流水表添加流水记录
        //积分流水表添加流水数据
        PointsFlow pointsFlow = new PointsFlow();
        pointsFlow.setUserId(userRoleInfo.getUserId());
        pointsFlow.setUserType(userRoleInfo.getUserType());
        pointsFlow.setChangeType(PointsFlowConstant.pointsExchange); //10-积分兑换
        pointsFlow.setChangeName(PointsFlowConstant.pointsExchangeName); //积分兑换
        pointsFlow.setChangePoints(0 - Integer.valueOf(points));
        pointsFlow.setUpOrDown(PointsFlowConstant.points_down);
        int pointsFlowNum = pointsFlowMapper.insert(pointsFlow);
        if(pointsFlowNum < 1){
            throw new RuntimeException("积分兑换-失败(2)");
        }
        //资金流水-积分兑换
        CapitalFlow capitalFlow2 = new CapitalFlow();
        capitalFlow2.setUserId(userRoleInfo.getUserId());
        capitalFlow2.setAccount(userBasic.getAccount());
        capitalFlow2.setUserType(userRoleInfo.getUserType());
        capitalFlow2.setChangeType(CapitalFlowTypeConstant.pointsExchange); //15-积分兑换
        capitalFlow2.setChangeName(CapitalFlowTypeConstant.pointsExchangeName); //积分兑换
        capitalFlow2.setBeforeChangeAmount(userRoleInfo.getBalance());
        capitalFlow2.setChangeAmount(new BigDecimal(amount));
        capitalFlow2.setAfterChangeAmount(userRoleInfo.getBalance().add(new BigDecimal(amount)));
        capitalFlow2.setUpOrDown(CapitalFlowTypeConstant.money_up);
        int capitalFlowNum = capitalFlowMapper.insert(capitalFlow2);
        if(capitalFlowNum < 1){
            throw new RuntimeException("积分兑换-失败(3)");
        }
        //公司流水-积分兑换支出
        CompanyFlow companyFlow = new CompanyFlow();
        companyFlow.setChangeType(CompanyFlowConstant.pointsExchange); //15-积分兑换支出
        companyFlow.setChangeName(CompanyFlowConstant.pointsExchangeName); //积分兑换支出
        companyFlow.setChangeAmount(new BigDecimal(amount).negate());
        companyFlow.setUpOrDown(CompanyFlowConstant.money_down);
        companyFlow.setUserId(userRoleInfo.getUserId());
        companyFlow.setUserType(userRoleInfo.getUserType());
        int companyFlowNum = companyFlowMapper.insert(companyFlow);
        if(companyFlowNum < 1){
            throw new RuntimeException("积分兑换-失败(4)");
        }

        return Result.OK("积分兑换成功");
    }



}
